package dao;

import domain.Orders;
import util.DbUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrdersDao {
    DbUtil dbUtil = new DbUtil();
    public int pageSize = 10;

    public Orders findOrderById (int id) {
        String sql = "select * from orders where id = "+id+" ";
        ResultSet rs = dbUtil.executeQuery(sql);
        try {
            if (rs.next()){
                return converToOrder(rs);
            }else {
                return null;
            }
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }

    public List<Orders> findOrderByUserId(int userId) {
        String sql = "select * from orders where user_id = "+userId+" ";
        System.out.println(sql);
        ResultSet rs = dbUtil.executeQuery(sql);
        List<Orders> list = new ArrayList<Orders>();
        try{
            while (rs.next()){
                Orders orders = converToOrder(rs);
                list.add(orders);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    public int getTotal(int user_id){
//        String sql= "select count(1) as total from car where user_id = "+896733+" ";
        String sql= "select count(1) as total from orders where user_id = "+user_id+" ";
        System.out.println(sql);
        ResultSet rs = dbUtil.executeQuery(sql);
        int total = 0;
        try {
            if (rs.next()) {
                total=rs.getInt("total");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return total;
    }


    public Orders converToOrder(ResultSet rs){
        Orders orders = null;
        try {
            int id = rs.getInt(1);
            String userid = rs.getString(2);
            String goodspic = rs.getString(3);
            String goodsprice = rs.getString(4);
            int num = rs.getInt(5);
            String address = rs.getString(6);
            String addressname = rs.getString(7);
            String phone = rs.getString(8);
            orders = new Orders(id,userid,goodspic,goodsprice,num,address,addressname,phone);
            return orders;
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }
}
